import { GetDefaultListConfig, GetModelListModels } from '@/common';
import { SvgIcon } from '@/components/icon';
import { Button } from 'antd';
import React, { useEffect, useMemo, useState } from 'react';
import ModelInput from '@/pages/modelManage/components/ModelInput';
import useModal from '@/hooks/use-modal/useModal';
import ModelAdd from '@/pages/modelManage/components/ModelAdd';
import { useNavigate } from 'react-router-dom';

interface Props {
  list: any[];
  providerInfo: any[];
  getModelInfo: () => void;
  adminUser: boolean;
}

const ModelFailure = ({ list, providerInfo, getModelInfo, adminUser }: Props) => {
  // const appList = useMemo(() => list.map((item) => item.modelList)[0], [list]);

  const appList = useMemo(() => {
    // 假设每个 modelList 里 item 的结构是 { appId: string, ... }
    const allModelList = list.flatMap((item) => item.modelList || []);
    const dedupedMap = new Map();
    allModelList.forEach((model) => {
      // 以 appId 作为 key
      if (!dedupedMap.has(model.appId)) {
        dedupedMap.set(model.appId, model);
      }
    });
    return Array.from(dedupedMap.values());
  }, [list]);

  const [refresh, setRefresh] = useState(0);
  const [defaultModelAdd, setDefaultModelAdd] = useState<GetModelListModels>();
  const navigate = useNavigate();

  const modal = useModal('input', 'addModel');

  const handleInputOk = (value?: boolean) => {
    if (value) {
      getModelInfo();
      // getTables();
    }
    // setModelInputStatus(false);
    modal.input.close();
  };

  const addModelSubmit = () => {
    setRefresh(refresh + 1);
    modal.addModel.close();
  };

  const handleModelAddDefault = (value: GetModelListModels) => {
    setDefaultModelAdd(value);
    modal.addModel.open();
  };

  const handleModelAddClose = () => {
    modal.addModel.close();
    setDefaultModelAdd(undefined);
  };

  const handleJumpModelPages = () => {
    navigate('/worklayouts/modelManage');
  };

  return (
    <div className="mb-4 h-[54px] rounded-md border-[1px] border-solid border-@warning-color-disabled bg-@warning-color-light px-4 py-3">
      <div className="mb-1 flex items-center gap-2 text-sm leading-[22px]">
        <div className="flex h-6 w-4 items-center justify-center">
          <SvgIcon icon="warning" size={16} color="#FF9226" />
        </div>
        {/* <span className="font-semibold text-text-5">{`${list
          .slice(0, 3)
          .map((item, index) => `${item.provider}`)}${
          list.length > 3 ? `等${list.length - 3}厂商` : ''
        }已失效，相关应用无法使用`}</span> */}

        <span className="font-semibold text-text-5">
          {list.slice(0, 2).map((item, index, arr) => (
            <React.Fragment key={item.model}>
              {/* 黄色 */}
              <span>{item.model}</span>
              {/* 逗号分隔符，只有不是最后一个时显示 */}
              {index < arr.length - 1 && <span>，</span>}
            </React.Fragment>
          ))}
          {list.length > 2 ? (
            <>
              等<span className="font-semibold"> {list.length - 2} </span>个模型
            </>
          ) : (
            ''
          )}
          已失效，
          {appList.slice(0, 3).map((item, index) => (
            <React.Fragment key={item.id ?? index}>
              <span className="font-semibold">{item.name}</span>
              {index < appList.slice(0, 3).length - 1 ? '，' : ''}
            </React.Fragment>
          ))}
          {appList.length > 3 ? (
            <>
              ... 等<span className="font-semibold"> {appList.length - 3} </span>个应用
            </>
          ) : (
            ''
          )}已无法使用，请及时
          {adminUser ? (
            list.length > 1 ? (
              <a onClick={handleJumpModelPages} className="!text-@brand-color !underline">
                去处理
              </a>
            ) : (
              <a type="primary" onClick={modal.input.open} className="!text-@brand-color !underline">
                处理
              </a>
            )
          ) : (
            <></>
          )}
        </span>


      </div>
      {/* <div className="flex">
        <div className="w-6" />
        <span className="text-cn-12 text-text-3">
          {appList.slice(0, 3).map((item, index) => (
            <React.Fragment key={item.id ?? index}>
              <span className="font-semibold">{item.name}</span>
              {index < appList.slice(0, 3).length - 1 ? '，' : ''}
            </React.Fragment>
          ))}
          {appList.length > 3 ? (
            <>
              ... 等<span className="font-semibold"> {appList.length - 3} </span>个应用
            </>
          ) : (
            ''
          )}
          已无法正常使用，{adminUser ? '请及时处理' : '请联系管理员解决或进入应用更换模型'}
        </span>
      </div> */}

      {/* <div className="mt-2 flex">
        <div className="h-6 w-6" />
        {adminUser ? (
          list.length > 1 ? (
            <a onClick={handleJumpModelPages}>去处理</a>
          ) : (
            <a type="primary" onClick={modal.input.open}>
              处理
            </a>
          )
        ) : (
          <></>
        )}
      </div> */}

      <ModelInput
        modelData={providerInfo[0]}
        open={modal.input.isOpen}
        onCancel={modal.input.close}
        onSubmit={handleInputOk}
        updateModel={modal.addModel.open}
        refresh={refresh}
        openSetting={handleModelAddDefault}
        status={true}
        // title={providerInfo[0].name + '配置编辑'}
        title={'配置编辑'}
      />

      <ModelAdd
        open={modal.addModel.isOpen}
        onCancel={handleModelAddClose}
        onOk={addModelSubmit}
        modelData={providerInfo[0]}
        defaultValue={defaultModelAdd}
      />
    </div>
  );
};

export default ModelFailure;
